package com.mmz.security.browser;

import com.mmz.security.browser.support.SimpleResponse;
import com.mmz.security.core.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class BrowserSecurityController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 说明:
     *  接到请求以后,是否需要身份验证,这个判断是框架做的,如果需要身份验证,会做一个跳转,根据.loginPage("/authentication/require")
     *  配置,来决定跳到哪里,如果没有配置,会有默认的配置.
     *  在执行跳转之前,框架用HttpSessionRequestCache这个类,把当前请求,缓存到session里面去.
     *  所以,在跳转到/authentication/require请求以后,我们可以再用这个类,把之前存到session里面的请求(savedRequest)拿出来
     */
    private RequestCache requestCache = new HttpSessionRequestCache();

    // spring 的跳转工具类
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Autowired
    private SecurityProperties securityProperties;

    @RequestMapping("/authentication/require")
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED) // 返回状态码
    public SimpleResponse requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {

        SavedRequest savedRequest = requestCache.getRequest(request,response);
        if (savedRequest != null) {
            // 引发跳转的url
            String redirectUrl = savedRequest.getRedirectUrl();
            logger.info("引发跳转的请求url为: " + redirectUrl);
            if (StringUtils.endsWithIgnoreCase(redirectUrl,".html")){
                System.out.println("配置允许访问的url为: " + securityProperties.getBrowser().getLoginPage());
                redirectStrategy.sendRedirect(request,response,securityProperties.getBrowser().getLoginPage());
            }
        }
        return new SimpleResponse("访问的服务需要身份验证,请引导用户到登录页");
    }
}
